
<template>
  <div class="charts-container">
    <div class="chart-wrapper">
      <el-button @click="fetchBarChartData">刷新柱状图数据</el-button>
      <div ref="barChartRef" class="chart"></div>
    </div>
    <div class="chart-wrapper">
      <el-button @click="fetchPopulationPieChartData">刷新人口饼状图数据</el-button>
      <div ref="populationPieChartRef" class="chart"></div>
    </div>
    <div class="chart-wrapper">
      <el-button @click="fetchAffairsPieChartData">刷新事务饼状图数据</el-button>
      <div ref="affairsPieChartRef" class="chart"></div>
    </div>
    <div class="chart-wrapper">
      <el-button @click="fetchAffairsLineChartData">刷新事务折线图数据</el-button>
      <div ref="affairsLineChartRef" class="chart"></div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue';
import axios from '@/utils/axios';
import * as echarts from 'echarts';

const barChartRef = ref(null);
const populationPieChartRef = ref(null);
const affairsPieChartRef = ref(null);
const affairsLineChartRef = ref(null);
let barChartInstance = null;
let populationPieChartInstance = null;
let affairsPieChartInstance = null;
let affairsLineChartInstance = null;

const barChartData = ref([]);
const populationPieChartData = ref([]);
const affairsPieChartData = ref([]);
const affairsLineChartData = ref([]);

const fetchBarChartData = async () => {
  try {
    const response = await axios.get('http://127.0.0.1:9000/chart/getPolice'); // 替换为你的后端接口
    if (response.data.code === 2000) {
      barChartData.value = response.data.data;
      updateBarChart();
    } else {
      console.error('获取柱状图数据失败', response.data.message);
    }
  } catch (error) {
    console.error('获取柱状图数据失败', error);
  }
};

const fetchPopulationPieChartData = async () => {
  try {
    const response = await axios.get('http://127.0.0.1:9000/chart/getPopulation'); // 替换为你的后端接口
    if (response.data.code === 2000) {
      populationPieChartData.value = response.data.data;
      updatePopulationPieChart();
    } else {
      console.error('获取人口饼状图数据失败', response.data.message);
    }
  } catch (error) {
    console.error('获取人口饼状图数据失败', error);
  }
};

const fetchAffairsPieChartData = async () => {
  try {
    const response = await axios.get('http://127.0.0.1:9000/chart/getEvent'); // 替换为你的后端接口
    if (response.data.code === 2000) {
      affairsPieChartData.value = response.data.data;
      updateAffairsPieChart();
    } else {
      console.error('获取事务饼状图数据失败', response.data.message);
    }
  } catch (error) {
    console.error('获取事务饼状图数据失败', error);
  }
};

const fetchAffairsLineChartData = async () => {
  try {
    const response = await axios.get('http://127.0.0.1:9000/chart/getTime'); // 替换为你的后端接口
    if (response.data.code === 2000) {
      affairsLineChartData.value = response.data.data;
      updateAffairsLineChart();
    } else {
      console.error('获取事务折线图数据失败', response.data.message);
    }
  } catch (error) {
    console.error('获取事务折线图数据失败', error);
  }
};

const updateBarChart = () => {
  if (barChartInstance) {
    const stationNames = barChartData.value.map(item => item.name);
    const policeNums = barChartData.value.map(item => item.policeNum);

    barChartInstance.setOption({
      title: {
        text: '警察局警员数量',
      },
      tooltip: {
        trigger: 'axis',
      },
      xAxis: {
        type: 'category',
        data: stationNames,
      },
      yAxis: {
        type: 'value',
      },
      series: [
        {
          name: '警员数量',
          data: policeNums,
          type: 'bar',
        },
      ],
    });
  }
};

const updatePopulationPieChart = () => {
  if (populationPieChartInstance) {
    const formattedData = populationPieChartData.value.map(item => {
      const [name, value] = item.split(':');
      return { name, value: parseInt(value) };
    });

    populationPieChartInstance.setOption({
      title: {
        text: '人口分布',
        left: 'center'
      },
      tooltip: {
        trigger: 'item'
      },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      series: [
        {
          name: '人口数量',
          type: 'pie',
          radius: '50%',
          data: formattedData,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    });
  }
};

const updateAffairsPieChart = () => {
  if (affairsPieChartInstance) {
    const formattedData = affairsPieChartData.value.map(item => {
      const [name, value] = item.split(':');
      return { name, value: parseInt(value) };
    });

    affairsPieChartInstance.setOption({
      title: {
        text: '事务分布',
        left: 'center'
      },
      tooltip: {
        trigger: 'item'
      },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      series: [
        {
          name: '事务数量',
          type: 'pie',
          radius: '50%',
          data: formattedData,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    });
  }
};

const updateAffairsLineChart = () => {
  if (affairsLineChartInstance) {
    const formattedData = affairsLineChartData.value.map(dateString => {
      // 从字符串中提取日期
      const date = new Date(dateString);
      return date.toISOString().split('T')[0]; // 提取日期部分
    });

    // 统计每个日期出现的次数
    const dateCounts = formattedData.reduce((acc, date) => {
      if (!acc[date]) {
        acc[date] = 1;
      } else {
        acc[date]++;
      }
      return acc;
    }, {});

    // 将日期和对应事务数量转换为数组并按日期排序
    const sortedData = Object.entries(dateCounts).sort((a, b) => new Date(a[0]) - new Date(b[0]));

    const xAxisData = sortedData.map(item => item[0]); // 获取排序后的日期
    const seriesData = sortedData.map(item => item[1]); // 获取排序后的事务数量

    affairsLineChartInstance.setOption({
      title: {
        text: '事务办理数量变化趋势',
        left: 'center'
      },
      tooltip: {
        trigger: 'axis'
      },
      xAxis: {
        type: 'category',
        data: xAxisData // 日期
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          name: '事务数量',
          type: 'line',
          data: seriesData // 对应的事务数量
        }
      ]
    });
  }
};

onMounted(() => {
  barChartInstance = echarts.init(barChartRef.value);
  populationPieChartInstance = echarts.init(populationPieChartRef.value);
  affairsPieChartInstance = echarts.init(affairsPieChartRef.value);
  affairsLineChartInstance = echarts.init(affairsLineChartRef.value);

  fetchBarChartData();
  fetchPopulationPieChartData();
  fetchAffairsPieChartData();
  fetchAffairsLineChartData();
});

</script>

<style scoped>
.charts-container {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
  margin-top: 10px;
  max-height: 1500px; /* 设置最大高度 */
  overflow: auto; /* 添加滚动条 */
}

.chart-wrapper {
  flex: 0 0 calc(50% - 20px);
  margin: 10px;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
}

.chart {
  height: 250px;
}

</style>
